package com.lkd.http.controller;

import com.lkd.common.VMSystem;
import com.lkd.entity.OrderEntity;
import com.lkd.service.OrderService;
import com.lkd.utils.ConvertUtils;
import com.lkd.vo.PayVO;
import com.lkd.wxpay.WXConfig;
import com.lkd.wxpay.WxPayDTO;
import com.lkd.wxpay.WxPaySDKUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private WxPaySDKUtil wxPaySDKUtil;


    @PostMapping("/requestPay")
    public String createOrder(PayVO payVO) {
        //创建订单
        OrderEntity order = orderService.createOrder(payVO);

        WxPayDTO wxPayDTO=new WxPayDTO();
        wxPayDTO.setBody(order.getSkuName());
        wxPayDTO.setOpenid(order.getOpenId());
        wxPayDTO.setTotalFee(order.getAmount());
        wxPayDTO.setOutTradeNo(order.getOpenId());

        return wxPaySDKUtil.requestPay(wxPayDTO);
    }

    /**
     * 微信支付回调接口
     * @param request
     * @return
     */
    @RequestMapping("/payNotify")
    public void payNotify(HttpServletRequest request, HttpServletResponse response){
        log.info("调用了回调方法");
        try {
           String notifyResult = ConvertUtils.convertToString(request.getInputStream());
//            //验证支付结果，返回订单编号，因为没有本地穿透，所以固定订单编号
//            String orderSn = wxPaySDKUtil.validPay(notifyResult);
            //订单编号
            String orderSn="";
            if (orderSn!=null){
                log.info("修改订单状态和支付状态");
                //查询订单
                OrderEntity orderEntity = orderService.getByOrderNo(orderSn);
                if (orderEntity!=null){

                    // 订单状态：支付完成
                    orderEntity.setStatus(VMSystem.ORDER_STATUS_PAYED);
                    // 订单支付状态：支付完成
                    orderEntity.setPayStatus(VMSystem.PAY_STATUS_PAYED);
                    orderService.updateById(orderEntity);
                    //返回维修成功响应
                    response.setContentType("text/xml");
                    response.getWriter().write(WXConfig.RESULT);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
